import os
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import ImageUploadSerializer, CheckImageSerializer
from .deep_model import deep_model_check_image


class ImageUploadView(APIView):
    def post(self, request):
        serializer = ImageUploadSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class CheckImageView(APIView):
    def post(self, request):
        serializer = CheckImageSerializer(data=request.data)
        if serializer.is_valid():
            base_path = os.path.join(os.getcwd(), 'server', 'media')  # 根据需要调整基路径
            file_name = serializer.validated_data.get('img_path')  # 获取request中的path
            full_path = os.path.join(base_path, file_name)
            result = deep_model_check_image(full_path)  # 调用deep_model_check_image(path)
            return Response({'result': result}, status=status.HTTP_200_OK)  # 返回结果
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
